package com.cy.law.filter;

import com.cy.law.utils.JSONUtil;
import com.cy.law.utils.SessionUtil;
import com.cy.law.vo.CodeMessage;
import com.cy.law.vo.RequestResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * @Author: caiqyxyx
 * @Date: 2018/8/27 15:54
 * 过滤没有权限的请求
 */
public class SessionFilter implements Filter {
    private final static Logger logger = LoggerFactory.getLogger(SessionFilter.class);

    public SessionFilter() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        if (SessionUtil.sessionInvalid(req)) {
            chain.doFilter(servletRequest, servletResponse);
        } else {
            errorSession(req, (HttpServletResponse) servletResponse);
        }
    }

    @Override
    public void destroy() {

    }

    private void errorSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // todo
        RequestResult requestResult = RequestResult.new0().setCodeMessage(CodeMessage.UNAUTHORIZED);
        //如果是Ajax请求
        if ("XMLHttpRequest".equals(req.getHeader("X-Requested-With"))) {
            // 401 session失效
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter out = null;
            try {
                out = resp.getWriter();
                out.println(JSONUtil.toString(requestResult));
                out.flush();
            } catch (IOException e) {
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } else {
            //如果是非Ajax请求
            RequestDispatcher rd = req.getRequestDispatcher("/view/error/errinfo.jsp");
            req.setAttribute("requestResult", requestResult);
            rd.forward(req, resp);
        }
    }
}